﻿namespace Grep.SharePoint.Lib.Extensions
{
    using System;
    using System.Reflection;
    using Grep.Lib.Extensions;
    using Grep.Lib.Web.UI.Extensions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.WebPartPages;

    internal static class ListViewWebPartExtensions
    {
        public static SPList GetList(this ListViewWebPart self)
        {
            return SPContext.Current.Web.Lists[new Guid(self.ListName)];
        }

        public static NewMenu GetNewMenu(this ListViewWebPart self)
        {
            return self.FindChildByType<NewMenu>();
        }

        public static string GetRootFolder(this ListViewWebPart self, bool relative)
        {
            var rootFolder =
                ((string)
                 self.GetType().GetField("rootFolder", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(self));
            if (!string.IsNullOrEmpty(rootFolder))
            {
                return SPContext.Current.Web.Url.GreedyAppend(rootFolder, relative);
            }
            return (relative ? "" : SPContext.Current.Web.Url) + "/" + self.GetList().RootFolder.Url;
        }

        public static UploadMenu GetUploadMenu(this ListViewWebPart self)
        {
            return self.FindChildByType<UploadMenu>();
        }
    }
}